<template>
  <div class="pages fwxm">
    <div class="pageLevel" v-if="!sub">
      <div class="tableSearch">
        <el-form label-width="15px" size="small">
          <el-form-item label label-width="0">
            <el-input clearable v-model="selectdata.keyword" placeholder="请输入服务名称搜索"></el-input>
          </el-form-item>
          <el-form-item label label-width="20px">
            <el-select
              v-model="selectdata.status"
              placeholder="请选择状态"
              size="small"
              style="width:150px;"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="销售是否提成" label-width="100px" v-if="!(soUrce !=5&&isShop==0)">
            <el-select
              v-model="selectdata.saleCommission"
              placeholder="请选择状态"
              size="small"
              style="width:150px;"
            >
              <el-option
                v-for="item in commissionOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="劳动是否提成" label-width="100px" v-if="!(soUrce !=5&&isShop==0)">
            <el-select
              v-model="selectdata.workCommission"
              placeholder="请选择状态"
              size="small"
              style="width:150px;"
            >
              <el-option
                v-for="item in commissionOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label>
            <el-button type="primary" @click="searchSelect()">查询</el-button>
            <el-button type="primary" v-if="setRole('新增服务项目')" @click="clickAdd()">新增服务</el-button>
            <el-button type="primary" v-if="setRole('分配门店')" @click=" assignStore()">分配门店</el-button>
            <el-button type="primary" v-if="setRole('设置销售提成')&&!(soUrce !=5&&isShop==0)" @click="onSetCommission(0)">设置销售提成</el-button>
            <el-button type="primary" v-if="setRole('设置劳动提成')&& !(soUrce !=5&&isShop==0)" @click="onSetCommission(1)">设置劳动提成</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="tableMain">
        <el-table
          ref="multipleTable"
          :data="tableData"
          @selection-change="handleSelectionChange"
          stripe
          style="width: 100%"
        >
          <el-table-column type="selection" width="50" :selectable="selectInit"></el-table-column>
          <el-table-column prop="name" align="center" label="服务名"></el-table-column>
          <el-table-column prop="serviceTime" align="center" label="时长"></el-table-column>
          <el-table-column prop="price" align="center" label="价格"></el-table-column>
          <el-table-column prop="state" align="center" :formatter="states" label="状态"></el-table-column>
          <el-table-column property="saleRoyalty" align="center" label="销售是否提成" v-if="!(soUrce !=5&&isShop==0)">
             <template slot-scope="scope">
              <span v-if="scope.row.saleRoyalty === 0">否</span>
              <span v-if="scope.row.saleRoyalty === 1">是</span>
            </template>
          </el-table-column>
          <el-table-column property="deductAmount" align="center" label="销售提成比例/金额" v-if="!(soUrce !=5&&isShop==0)">
          <template slot-scope="scope">
            <span v-if="scope.row.saleRoyalty == 1">
              {{scope.row.deductAmount}}
              <span v-if="scope.row.deductType == 0">%</span>
              <span v-if="scope.row.deductType == 1">元</span>
            </span>
            <span v-if="scope.row.saleRoyalty == 0">
                --
            </span>
            </template>
          </el-table-column>
          <el-table-column property="labourRoyalty" align="center" label="劳动是否提成" v-if="!(soUrce!= 5 && isShop==0)">
            <template slot-scope="scope">
              <span v-if="scope.row.labourRoyalty === 0">否</span>
              <span v-if="scope.row.labourRoyalty === 1">是</span>
            </template>
          </el-table-column>
          <el-table-column property="labourDeductAmount" align="center" label="劳动提成比例/金额" v-if="!(soUrce!= 5 && isShop==0)">
            <template slot-scope="scope">
              <span v-if="scope.row.labourRoyalty == 1">
                 {{scope.row.labourDeductAmount}}
                 <span v-if="scope.row.labourDeductType == 0">%</span>
                 <span v-if="scope.row.labourDeductType == 1">元</span>
             </span>
             <span v-if="scope.row.labourRoyalty == 0">
                --
             </span>
            </template>
          </el-table-column>
          <el-table-column prop="visit" align="center" label="回访周期">
            <template slot-scope="scope">
              <span v-if="scope.row.visit">{{scope.row.visit}}天</span>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column prop="name" align="center" label="操作" width="180">
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                v-if="setRole('查看分配门店')"
                @click="handleViewStore(scope.row.id)"
              >查看分配门店</el-button>
              <el-button
                type="text"
                size="small"
                v-if="setRole('编辑服务项目')"
                @click="clickEdit(scope.row.id)"
              >编辑</el-button>
              <el-button
                type="text"
                size="small"
                v-if="setRole('删除')"
                @click="detelefx(scope.row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <page-unit :pageData="pageData" :func="serverlist"></page-unit>

        <!-- 分配门店对话框 -->
        <el-dialog
          class="discount-css addshopname"
          title="选择门店"
          :close-on-click-modal="false"
          :close-on-press-escape="false"
          :visible.sync="dialogVisible_store"
          width="50%"
        >
          <div class="prices service-tips-box">
            <el-form>
              <el-form-item>
                <el-input
                  size="small"
                  class="inp-sr"
                  v-model="selectdata.keywordStoreNo"
                  placeholder="请输入门店名称或编号"
                ></el-input>
                <el-button size="small" type="primary" @click="handleFenpei_do_search">搜索</el-button>
              </el-form-item>
            </el-form>
            <el-table
              height="300"
              :data="store_fenpei"
              @selection-change="changeFun_addStore"
              border
            >
              <el-table-column
                type="selection"
                width="55"
                class="selection"
                property="shopId"
                label="选择"
                align="center"
              ></el-table-column>
              <el-table-column property="shopName" align="center" label="门店名称"></el-table-column>
              <el-table-column property="shopCode" align="center" label="编号"></el-table-column>
            </el-table>
            <span
              slot="footer"
              class="dialog-footer dialog-footer-top"
              style="display: inline-block; margin-top:20px;margin-left: 38%;"
            >
              <el-button
                class="dialog-footer-button"
                size="small"
                type="primary"
                @click="handleFenpei_s()"
              >分配服务</el-button>
              <el-button
                class="dialog-footer-button"
                size="small"
                @click="dialogVisible_store = false"
              >取 消</el-button>
            </span>
          </div>
          <!--------分配服务提示---------->
          <el-dialog
            class="discount-css addshopname"
            title="分配服务提示"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            :visible.sync="dialogVisible_tips"
            width="50%"
            append-to-body
          >
            <div class="service-tips-box">
              <p>注：服务中含有的商品，您所选择的门店无报货权限，请查看未分配商品并进行分配</p>
              <el-table max-height="300" :data="goods_fenpei" border>
                <el-table-column type="index" width="55" label="序号" align="center"></el-table-column>
                <el-table-column property="shopName" align="center" label="门店名称"></el-table-column>
                <el-table-column property="shopCode" align="center" label="编号"></el-table-column>
                <el-table-column align="center" label="提醒">
                  <template slot-scope="scope">
                    <span v-if="scope.row.remind == 0">分配成功</span>
                    <el-button
                      v-else
                      type="text"
                      @click="findGoodsIdList(scope.$index)"
                      icon="el-icon-warning"
                      style="color: rgb(245,108,108)"
                    >查看未分配商品</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <div class="service-tips-box-bot">
                <el-button type="primary" size="small" @click="dealAllGoods(0)">一键快速分配商品</el-button>
                <el-button size="small" @click="dialogVisible_tips = false">取 消</el-button>
              </div>
            </div>
            <!------------单个门店分配商品-------------->
            <template v-if="dialogVisible_dealGoods">
              <el-dialog
                class="discount-css addshopname"
                :title="goods_fenpei[failStoreIndex].shopName"
                :close-on-click-modal="false"
                :close-on-press-escape="false"
                :visible.sync="dialogVisible_dealGoods"
                width="60%"
                append-to-body
              >
                <el-table max-height="300" :data="goods_fenpeiItem" border>
                  <el-table-column type="index" width="55" label="序号" align="center"></el-table-column>
                  <el-table-column property="barCode" align="center" label="商品条码"></el-table-column>
                  <el-table-column property="goodsCode" align="center" label="商品货号"></el-table-column>
                  <el-table-column property="name" align="center" label="商品名称"></el-table-column>
                  <el-table-column property="primaryClassify" align="center" label="分类"></el-table-column>
                  <el-table-column property="brand" align="center" label="品牌"></el-table-column>
                  <el-table-column property="parameter" align="center" label="规格型号">
                    <template slot-scope="scope">
                      <span
                        v-for="(item, index) in scope.row.parameter"
                        :key="index"
                      >{{item.paramName}}:{{item.paramValue}}</span>
                    </template>
                  </el-table-column>
                  <el-table-column property="unitName" align="center" label="单位"></el-table-column>

                  <el-table-column
                    property="status"
                    align="center"
                    label="是否启用"
                    :formatter="statust"
                  ></el-table-column>
                </el-table>
                <div class="service-tips-box-bot">
                  <el-button type="primary" size="small" @click="dealAllGoods(1)">全部分配</el-button>
                  <el-button size="small" @click="dialogVisible_dealGoods = false">取 消</el-button>
                </div>
              </el-dialog>
            </template>
          </el-dialog>
        </el-dialog>

        <!-- 查看分配门店对话框 -->
        <el-dialog
          class="discount-css"
          title="已分配门店-活动名称"
          :close-on-click-modal="false"
          :close-on-press-escape="false"
          :visible.sync="dialogVisible_check_store"
          width="50%"
        >
          <div class="prices">
            <el-form>
              <el-form-item class="gys">
                <el-input
                  size="small"
                  class="inp-sr"
                  v-model="selectdata.keywordStoreHas"
                  placeholder="请输入门店名称或编号搜索"
                ></el-input>
                <el-button size="small" type="primary" @click="handleAssigbSearch">搜索</el-button>
              </el-form-item>
            </el-form>
            <el-table max-height="300" :data="tableDataStore" border>
              <el-table-column prop="shopName" align="center" label="门店名称"></el-table-column>
              <el-table-column prop="shopCode" align="center" label="编号"></el-table-column>
              <el-table-column align="center" label="操作" v-if=" isShop == 1">
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    size="small"
                    @click="handleCancelAssign(scope.row.shopId)"
                  >取消分配</el-button>
                </template>
              </el-table-column>
            </el-table>
            <span
              slot="footer"
              class="dialog-footer dialog-footer-top"
              style="display: inline-block; margin-top:20px;margin-left: 42%;"
            >
              <el-button
                class="dialog-footer-button"
                size="small"
                @click="dialogVisible_check_store = false"
              >返回</el-button>
            </span>
          </div>
        </el-dialog>
        <!-- 设置提成 -->
        <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" class="commission-dialog">
          <el-form :model="dialogForm" label-width="100px" size="mini">
            <el-form-item label="是否提成">
              <el-radio-group v-model="dialogForm.isCommission">
                <el-radio label="1">是</el-radio>
                <el-radio label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="选择提成方式" v-if="dialogForm.isCommission ==1">
              <el-select v-model="dialogForm.commissionType">
                <el-option label="比例提成" value="0"></el-option>
                <el-option label="固定提成" value="1"></el-option>
              </el-select>
              <el-input v-model="dialogForm.number"></el-input>
              <span v-if="dialogForm.commissionType == 0">%</span>
              <span v-else>元</span>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false" size="samll">取 消</el-button>
            <el-button type="primary" @click="onConfirmSet" size="samll">确 定</el-button>
          </div>
        </el-dialog>
      </div>
    </div>
    <div class="pageLevel" v-else>
      <router-view></router-view>
    </div>
  </div>
</template>
<script>
import { mapState } from "vuex";
import pageUnit from "@/components/Page";
import u from "@/util";
import s from "@/util/state";
import {
  serviceListPage,
  removeService,
  getShopList,
  saveServiceOrShop,
  getServiceShopListPage,
  deleteShop,
  deleteServiceOrShop,
  findGoodsIdListByGoodsShop,
  toLowerShop,
  addRoyalty // 批量设置提成
} from "@/api";

export default {
  components: { pageUnit },
  computed: mapState(["sub", "power", "merchantId", "isShop", "soUrce"]),
  data() {
    return {
      statust: s.status, //列表中是否启用转化
      selectdata: {
        keyword: "",
        keywordStoreNo: "",
        keywordStoreHas: "",
        status: null,
        saleCommission: null,
        workCommission: null
      },
      tableData: [],
      multipleSelections: [],
      dialogVisible_store: false,
      dialogVisible_tips: false, //分配提示
      dialogVisible_dealGoods: false, //门店分配
      store_fenpei: [],
      multipleSelection_store_s: [],
      dialogVisible_check_store: false,
      handleViewStore_id: "",
      tableDataStore: [],
      multipleSelection_store: [],
      goods_fenpei: [], //门店商品情况
      goods_fenpeiItem: [], //门店未分配商品
      failStoreIndex: null, //失败门店index
      pageData: {
        pageSize: 20,
        currentPage: 1,
        totalItems: 0,
        pageSizeArr: [5, 10, 20]
      },
      pageDataStore: {
        pageSize: 20,
        currentPage: 1,
        totalItems: 0,
        pageSizeArr: [5, 10, 20]
      },
      options: [
        {
          label: "全部",
          value: null
        },
        {
          label: "上架",
          value: 0
        },
        {
          label: "下架",
          value: 1
        }
      ],
      commissionOption: [
        {
          label: "全部",
          value: null
        },
        {
          label: "否",
          value: 0
        },
        {
          label: "是",
          value: 1
        }
      ],
      dialogTitle: "",
      dialogFormVisible: false,
      dialogForm: {
        isCommission: "1",
        commissionType: "1",
        number: ""
      },
      commissionType: 0
    };
  },
  mounted() {
    if (!this.sub) {
      this.serverlist(20, 1);
    }
  },
  watch: {
    sub: {
      handler: function(val, oldVal) {
        if (oldVal != null && val == false) {
          this.serverlist(20, 1);
        }
      },
      deep: true
    }
  },
  methods: {
    selectInit(row, index) {
      if (row.state == 1) {
        return false;
      } else {
        return true;
      }
    },
    //查询未分配商品
    findGoodsIdList(index) {
      this.failStoreIndex = index;
      let data = {
        goodsIdList: this.goods_fenpei[index].goodsList,
        flag: 1
      };
      findGoodsIdListByGoodsShop(data).then(res => {
        this.goods_fenpeiItem = res.data;
        this.dialogVisible_dealGoods = true;
      });
    },
    //分配产品
    dealAllGoods(type) {
      let goodsIdsList = "";
      let shopIdsList = "";
      //全部分配
      if (type == 0) {
        this.$confirm(
          "提示：快速分配商品前请确认该服务是否匹配已选择的门店",
          "一键快速分配商品",
          {
            confirmButtonText: "分配",
            cancelButtonText: "取消",
            center: true,
            showClose: false
          }
        )
          .then(() => {
            let goods = this.goods_fenpei;
            for (let i = 0; i < goods.length; i++) {
              if (goods[i].remind == 1) {
                goodsIdsList += `${goods[i].goodsList},`;
                shopIdsList += `${goods[i].shopId},`;
              }
            }
            this.$nextTick(() => {
              toLowerShop({
                goodsIds: goodsIdsList,
                shopIds: shopIdsList
              }).then(res => {
                if (res.code == 200) {
                  this.$message.success("分配成功");
                  this.dialogVisible_tips = false;
                }
              });
            });
          })
          .catch(() => {});
      } else {
        let arr1 = this.goods_fenpei[this.failStoreIndex].goodsList;
        shopIdsList = this.goods_fenpei[this.failStoreIndex].shopId;
        for (let i = 0; i < arr1.length; i++) {
          goodsIdsList += `${arr1[i]},`;
        }
        this.$nextTick(() => {
          toLowerShop({
            goodsIds: goodsIdsList,
            shopIds: shopIdsList
          }).then(res => {
            if (res.code == 200) {
              {
                this.$message.success("分配成功");
                this.$set(this.goods_fenpei[this.failStoreIndex], "remind", 0);
                this.dialogVisible_dealGoods = false;
                for (let i = 0; i < this.goods_fenpei.length; i++) {
                  if (this.goods_fenpei[i].remind == 1) {
                    return;
                  }
                }
                this.dialogVisible_tips = false;
              }
            }
          });
        });
      }
    },
    states: s.states,
    setRole(key) {
      return u.selectTitle(this.power, key);
    },
    clickAdd() {
      if (this.soUrce == "5") {
        u.routerTo(
          "/operate-management/serve-management/service-management/service-add",
          {
            showTab: 1
          }
        );
      } else {
        u.routerTo(
          "/operate-management/serve-management/service-management/service-add"
        );
      }
    },
    clickEdit(id) {
      if (this.soUrce == "5") {
        u.routerTo(
          "/operate-management/serve-management/service-management/service-edit",
          {
            id: id,
            showTab: 2
          }
        );
      } else {
        u.routerTo(
          "/operate-management/serve-management/service-management/service-edit",
          {
            id: id
          }
        );
      }
    },
    serverlist(pageSize, pageNum) {
      let data = {
        pageNum: pageNum,
        pageSize: pageSize,
        companyId: this.merchantId,
        keyword: this.selectdata.keyword,
        status: this.selectdata.status,
        saleRoyalty: this.selectdata.saleCommission, //销售提成
        labourRoyalty: this.selectdata.workCommission //劳动提成
      };
      serviceListPage(data).then(res => {
        this.tableData = res.data.list;
        this.pageData.totalItems = res.data.totalRecord;
      });
    },
    searchSelect() {
      this.serverlist(this.pageData.pageSize, 1);
    },
    // 删除
    detelefx(id) {
      this.$confirm("确定要删除吗?", "提示", {
        center: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        closeOnClickModal: false,
        closeOnPressEscape: false
      })
        .then(() => {
          let data = {
            id: id
          };
          removeService(data).then(res => {
            if (res.code == 200) {
              this.$message.success(res.msg);
            } else {
              this.$message.error(res.msg);
            }
            this.serverlist(this.pageData.pageSize, 1);
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // 多选
    handleSelectionChange(val) {
      this.multipleSelections = val;
    },
    // 点击分配门店按钮
    assignStore() {
      if (this.multipleSelections.length > 0) {
        this.getShopList(this.pageDataStore.pageSize, 1);
        this.dialogVisible_store = true;
      } else {
        this.$message({
          showClose: true,
          message: "请先选择服务！",
          type: "error"
        });
      }
    },
    onSetCommission(type) {
      this.commissionType = type

      if (this.multipleSelections.length > 0) {
        if (type === 0) {
          this.dialogTitle = "设置销售提成";
        } else {
          this.dialogTitle = "设置劳动提成";
        }
        this.dialogFormVisible = true;
      } else {
        this.$message({
          showClose: true,
          message: "请先选择服务！",
          type: "error"
        });
      }
    },
    onConfirmSet() {
      if (this.dialogForm.isCommission == '1' && (!this.dialogForm.number || this.dialogForm.number == 0)) {
        this.$message.error('请输入提成值且大于0！')
        return
      }
      let data = {
        serviceIds: ""
      }, serviceIds=[];

      for (let i = 0; i < this.multipleSelections.length; i++) {
        const element = this.multipleSelections[i];
        serviceIds.push(element.id)
      }
      data.serviceIds = serviceIds.join(',')

      if (this.commissionType === 0) {
        this.dialogTitle = "设置销售提成";
        data.saleRoyalty = this.dialogForm.isCommission;
        data.deductType = this.dialogForm.commissionType;
        data.deductAmount = this.dialogForm.number;
      } else {
        this.dialogTitle = "设置劳动提成";
        data.labourRoyalty = this.dialogForm.isCommission;
        data.labourDeductType = this.dialogForm.commissionType;
        data.labourDeductAmount = this.dialogForm.number;
      }
      this.dialogFormVisible = true;
      addRoyalty(data).then(res => {
        if(res.code == 200) {
          this.dialogFormVisible = false;
          this.serverlist(this.pageData.pageSize, 1)
        }
      })
    },
    getShopList(pageSize, pageNum) {
      let data = {
        companyId: this.merchantId,
        pageSize: pageSize,
        pageNum: pageNum,
        keyword: this.selectdata.keywordStoreNo,
        flag: "1"
      };
      getShopList(data).then(res => {
        this.store_fenpei = res.data.list;
      });
    },
    handleFenpei_do_search() {
      this.getShopList(this.pageDataStore.pageSize, 1);
    },
    // 分配门店多选方法
    changeFun_addStore(val) {
      this.multipleSelection_store_s = val;
    },
    // 点击立即分配
    handleFenpei_s() {
      if (this.multipleSelection_store_s.length > 0) {
        let data = {
          serviceId: JSON.stringify(this.multipleSelections),
          shopId: JSON.stringify(this.multipleSelection_store_s)
        };
        saveServiceOrShop(data).then(res => {
          if (res.code == 200) {
            if (res.data == null && res.msg === "成功") {
              this.$message.success("分配成功");
              this.dialogVisible_store = false;
              this.serverlist(this.pageData.pageSize, 1);
              return;
            }
            this.goods_fenpei = res.data;
            this.dialogVisible_tips = true;
          }
        });
      } else {
        this.$message({
          type: "error",
          message: "请先选择门店!"
        });
      }
    },
    // 点击查看分配门店
    handleViewStore(id) {
      this.handleViewStore_id = id;
      this.getActivityShop();
      this.dialogVisible_check_store = true;
    },
    // 根据折扣id获取分配的门店
    getActivityShop() {
      let data = {
        serviceId: this.handleViewStore_id,
        keyword: this.selectdata.keywordStoreHas,
        pageSize: "20",
        pageNum: "1",
        flag: "1"
      };
      getServiceShopListPage(data).then(res => {
        this.tableDataStore = res.data.list;
      });
    },
    // 搜索分配门店
    handleAssigbSearch() {
      this.getActivityShop();
    },
    // 取消分配
    handleCancelAssign(id) {
      let data = {
        serviceId: this.handleViewStore_id,
        shopId: id
      };
      deleteServiceOrShop(data).then(res => {
        this.$message({
          type: "success",
          message: res.msg
        });
        this.getActivityShop();
      });
    }
  }
};
</script>
<style scoped>
.inp-sr {
  width: 300px;
}

.service-tips-box {
  padding: 0 30px;
}

.service-tips-box-bot {
  text-align: center;
  padding-top: 20px;
}

.service-tips-box > p {
  color: rgb(245, 108, 108);
  margin-bottom: 20px;
}
.commission-dialog .el-input {
  width: 100px;
}
</style>

